<?php
/**
 * Layout Helper
 *
 * PHP version 5
 *
 * @category Helper
 * @package  Croogo
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class SectionHelper extends AppHelper {
/**
 * Other helpers used by this helper
 *
 * @var array
 * @access public
 */
    var $helpers = null;
/**
 * Current Node
 *
 * @var array
 * @access public
 */
    var $node = null;
/**
 * Hook helpers
 *
 * @var array
 * @access public
 */
    var $hooks = array();
    
    
/**
 * Constructor
 *
 * @param array $options options
 * @access public
 */
    function __construct($options = array()) {
        $this->View =& ClassRegistry::getObject('view');
        //$this->__loadHooks();
		$this->helpers =& $this->View->helpers;
		//print_r($this->View);
		//$channels = $this->View->controller->Channel->find('threaded');
		//$model =  $this->getMedelObject('channel');
		
		//$model2 = &$this->getMedelObject('channelcontent');
		
		//print_r($model2);
		//echo "===========";
		//print_r($channels);
		//ClassRegistry::getObject('');
		
        return parent::__construct($options);
    }
    function &getMedelObject($modelClass)
    {
    	$model = false; 
    	if($model = & ClassRegistry::getObject($modelClass))
    	{
    		return $model;
    	}
    	else
    	{
    		$id = null;
    		return  ClassRegistry::init(array('class' => $modelClass, 'alias' => $modelClass, 'id' => $id));
    	}
    }
	
	function getNavMenu($type,$options)
	{
		$modelClass = 'Category';
		// 判断有模板缓存，不处理;注意不同页面，高亮显示的不一样。guid来对应html缓存内容
		// 判断有变量缓存，直接返回变量缓存
		// 若两个缓存都没有，则从数据库查出内容，返回
		$guid = guid_string($options);
//		$channels_html = Cache::read($type.$guid.'_menuhtml'); 
//		if ($channels_html !== false) {
//			return $channels_html;
//		}
//		else
		{
//			$channels = Cache::read($type.'_menu'); 
//			if ($channels === false) 
			{ 
				$model_obj = $this->getMedelObject($modelClass);
				//$model_obj->contain(); // 需要 var $actsAs = array('Containable'); 
				$model_obj->recursive = -1;
				 
				$channels = $model_obj->find('threaded',
					array('conditions'=>array('parent_id'=> null,'visible'=>1),
					'fields'=>array('id','title','slug','rel','target','link','parent_id'),
					));//'type'=>$type,
//				echo '<pre>';	print_r($channels);
				Cache::write($type.'_menu',$channels); 
			}
			$_options = array();		
			$_options = array(
	            'findOptions' => array(),
	            'tag' => 'ul',
	            'tagAttributes' => array(),
	            'containerTag' => 'div',
	            'containerTagAttr' => array(
	                'class' => 'menu',
	            ),
	            'defaultClass' => '',
	            'selectedClass' => 'item_active',
	            'selectedid' => '',
	            'dropdown' => true,
	            'dropdownClass' => '',
	        );	
	        $_options['modelclass']=$modelClass;
	        $options = array_merge($_options,$options);
			$channels_html = $this->nestedLinks($channels, $options);
			// 防止没有值时缓存设为空，判断不起作用，还是重查数据库
			if(empty($channels_html))
			{
				$channels_html=' ';
			}
			Cache::write($type.$guid.'_menuhtml',$channels_html); 
			return $channels_html;
		}
	}
	
	function getLeftMenu($type,$options)
	{
		$modelClass = 'Category';
		$parent_id = $options['parent_id'];
		// 判断有模板缓存，不处理
		// 判断有变量缓存，直接返回变量缓存
		// 若两个缓存都没有，则从数据库查出内容，返回
		$guid = guid_string($options);
		$channels_html = Cache::read($type.$guid.'_leftmenuhtml'); 
		if ($channels_html !== false) {
			return $channels_html;
		}
		else
		{
			$channels = Cache::read($type.$parent_id.'_leftmenu'); 
			if ($channels === false) 
			{ 
				$model_obj = $this->getMedelObject($modelClass);
				//$model_obj->contain(); // 需要 var $actsAs = array('Containable'); 
				$model_obj->recursive = -1;
				if($parent_id)
				{
					$parent_info = $model_obj->findById($parent_id);	
					$left = $parent_info['Category']['left'];
					$right = $parent_info['Category']['right'];
				}
				
				$channels = $model_obj->find('threaded',
					array('conditions'=>array('type'=>$type,'Category.left >'=> $left,'Category.right <'=> $right)));
				//print_r($channels);
				Cache::write($type.'_leftmenu',$channels); 
			}
			$_options = array();		
			$_options = array(
	            'findOptions' => array(),
	            'tag' => 'ul',
	            'tagAttributes' => array(),
	            'containerTag' => 'div',
	            'containerTagAttr' => array(
	                'class' => 'menu',
	            ),
	            'defaultClass' => 'ui-state-default',
	            'selectedClass' => 'ui-state-active',
	            'selectedid' => '',
	            'dropdown' => true,
	            'dropdownClass' => 'sf-menu sf-vertical',
	        );	
	        $_options['modelclass']=$modelClass;
	        $options = array_merge($_options,$options);
	        
			$channels_html = $this->nestedLinks($channels, $options);
			// 防止没有值时缓存设为空，判断不起作用，还是重查数据库
			if(empty($channels_html))
			{
				$channels_html=' ';
			}
			//print_r($_options);
			Cache::write($type.$guid.'_leftmenuhtml',$channels_html); 
			return $channels_html;
		}
	}
	
	function getRegionList($id)
	{
		$region = $this->getMedelObject('Region');
		
		$regioninfo = $region->read(null, $id);
		
		$modelname = $regioninfo['Region']['model'];
		$model = $this->getMedelObject($modelname );
		
		$model->recursive = -1; 
		$datas = $model->find('all', array(
            'conditions' => array(
                $modelname .'.user_id' => 1,
            ),
            'order' => $modelname .'.id DESC',
            'limit' => $regioninfo['Region']['rows'],
            'fields' => array(
                'id','title','created',
            ),
        ));        
        return $datas;
	}
/**
 * Nested Links
 *
 * @param array $links model output (threaded)
 * @param array $options (optional)
 * @param integer $depth depth level
 * @return string
 */
    function nestedLinks($links, $options = array(), $classname='',$depth = 1) {
        $_options = array();
        $options = array_merge($_options, $options);
        $modelName =  $options['modelclass'];
        $output = '';
        // 修改链接的格式，默认是不带有span的
        $this->Html->tags['link']='<a href="%s"%s><span>%s</span></a>';
        foreach ($links AS $link) {
            $linkAttr = array(
                'id' => 'link-' . $link[$modelName]['id'],
                'rel' => $link[$modelName]['rel'],
                'target' => $link[$modelName]['target'],
//                'title' => $link[$modelName]['description'],
            );

            foreach ($linkAttr AS $attrKey => $attrValue) {
                if ($attrValue == null) {
                    unset($linkAttr[$attrKey]);
                }
            }

            // if link is in the format: controller:contacts/action:view
            if (strstr($link[$modelName]['link'], 'controller:')) {
                $link[$modelName]['link'] = $this->linkStringToArray($link[$modelName]['link']);
            }

            if (Router::url($link[$modelName]['link']) == Router::url('/' . $this->params['url']['url'])) {
                $linkAttr['class'] = $options['selectedClass'];
            }
//			echo $modelName.'===';
			if(empty($link[$modelName]['link']))
			{
				if($link[$modelName]['slug'])
				{
					$link[$modelName]['link']='/'.$link[$modelName]['slug'];
				}
				else
				{
					$link[$modelName]['link']='/'.$link[$modelName]['id'];
				}
				//若没有指定链接， 则以表名/id 作为链接
			}
//			print_r($link[$modelName]);
			$linkOutput =$this->Html->link($link[$modelName]['title'], $link[$modelName]['link']);// 
//            $linkOutput = $this->Html->link($link[$modelName]['title'], $link[$modelName]['link'], $linkAttr);
//            echo  $linkOutput.'=========';
            if (isset($link['children']) && count($link['children']) > 0) {
                $linkOutput .= $this->nestedLinks($link['children'], $options, $depth + 1);
            }
            if($link[$modelName]['id'] == $options['selectedid'])
            {
            	$linkOutput = $this->Html->tag('li', $linkOutput,array('class'=>$options['selectedClass']) );
            }
            else
            {
            	$linkOutput = $this->Html->tag('li', $linkOutput,array('class'=>$options['defaultClass']) );
            }
            $output .= $linkOutput;
        }
        if ($output != null) {
            $tagAttr = array();
            if ($options['dropdown'] && $depth == 1) {
                $tagAttr['class'] = $options['dropdownClass'];
            }
            $output = $this->Html->tag($options['tag'], $output, $tagAttr);
        }

        return $output;
    }
/**
 * Converts strings like controller:abc/action:xyz/ to arrays
 *
 * @param string $link link
 * @return array
 */
    function linkStringToArray($link) {
        $link = explode('/', $link);
        $linkArr = array();
        foreach ($link AS $linkElement) {
            if ($linkElement != null) {
                $linkElementE = explode(':', $linkElement);
                if (isset($linkElementE['1'])) {
                    $linkArr[$linkElementE['0']] = $linkElementE['1'];
                } else {
                    $linkArr[] = $linkElement;
                }
            }
        }

        return $linkArr;
    }

/**
 * Filter content
 *
 * Replaces bbcode-like element tags
 *
 * @param string $content content
 * @return string
 */
    function filter($content) {
        $content = $this->filterElements($content);
        return $content;
    }
/**
 * Filter content for elements
 *
 * Original post by Stefan Zollinger: http://bakery.cakephp.org/articles/view/element-helper
 * [element:element_name] or [e:element_name]
 *
 * @param string $content
 * @return string
 */
    function filterElements($content) {
        preg_match_all('/\[(element|e):([A-Za-z0-9_\-]*)(.*?)\]/i', $content, $tagMatches);
        for ($i=0; $i < count($tagMatches[1]); $i++) {
            $regex = '/(\S+)=[\'"]?((?:.(?![\'"]?\s+(?:\S+)=|[>\'"]))+.)[\'"]?/i';
            preg_match_all($regex, $tagMatches[3][$i], $attributes);
            $element = $tagMatches[2][$i];
            $options = array();
            for ($j=0; $j < count($attributes[0]); $j++) {
                $options[$attributes[1][$j]] = $attributes[2][$j];
            }
            $content = str_replace($tagMatches[0][$i], $this->View->element($element,$options), $content);
        }
        return $content;
    }

}
?>